﻿using HartConfigTool.HARTCommands.CMDs;
using HartConfigTool.SerialPortUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HartConfigTool.UI.DebugWindow
{
    internal sealed class CMDsDebugWinHARTCMD1 : CMD1ReadPV
    {
        public CMDsDebugWinHARTCMD1(SerialPortsManager serialPortManager) : base(serialPortManager) { }
        protected override async Task SendCMDCode()
        {
            byte[] tempAry = new byte[16];
            byte[] cmdCodeBytes = null;

            if (serialPortManager.deviceID == 0xFFFFFFFF)
            {
                return;
            }

            CMD1ReadPVCMDCode.deviceIDH = (byte)(serialPortManager.deviceID >> 16);
            CMD1ReadPVCMDCode.deviceIDM = (byte)(serialPortManager.deviceID >> 8);
            CMD1ReadPVCMDCode.deviceIDL = (byte)(serialPortManager.deviceID >> 0);

            cmdCodeBytes = StructToBytes<CMD1ReadPVCMDCodeStruct>(CMD1ReadPVCMDCode);

            Array.Copy(cmdCodeBytes, 5, tempAry, 0, 8);
            cmdCodeBytes[cmdCodeBytes.Length - 1] = HARTProtocolV7.GetCRC(tempAry, (byte)8);

            serialPortManager.DebugMessage("[" + DateTime.Now + "]:-->" + HARTProtocolV7.HexToString(cmdCodeBytes) + "\r\n");

            await serialPortManager.SendCMD(cmdCodeBytes);
        }
        public override async Task ParseResponse(byte[] responseData)
        {
            await Task.Run(() =>
            {
                List<string> parts = new List<string>();
                byte[] bytes = null;
                byte[] data = null;
                string unit = null;

                data = serialPortManager.GetRxBufferData();

                bytes = HARTProtocolV7.GetDataFrame(data);

                // Debug Message
                serialPortManager.DebugMessage("[" + DateTime.Now + "]:<--" + HARTProtocolV7.HexToString(data) + "\r\n");

                // Primary Variable Units
                HARTProtocolV7.EngineeringUnitCodes.TryGetValue(bytes[10], out unit);
                parts.Add(unit);
                NotifyObservers(CMD1Observers, ObserversInfo.HARTCMD1Observers["PV Unit"], parts);
                // Primary Variable
                parts.Clear();
                parts.Add(BitConverter.ToSingle(bytes, 11).ToString());
                NotifyObservers(CMD1Observers, ObserversInfo.HARTCMD1Observers["PV"], parts);

                this.serialPortManager.RxDataClear();

                IsCompleted = true;
            });
        }
    }
}
